﻿using System;
using System.Windows.Forms;
using dk.Helper.Base;
using dk.Helper.Base.Core;

namespace dk.Helper.Controls
{
    public partial class WorldSelectorForm : Form
    {
        /// <summary>
        /// Address for slovak version of tribal wars.
        /// </summary>
        private const string DIVOKE_KMENE_ADDRESS = "divoke-kmene.sk";

        /// <summary>
        /// Game Server
        /// </summary>
        private readonly IGameServer gameServer;

        public WorldSelectorForm()
        {
            InitializeComponent();
            gameServer = new GameServer();
            gameServer.Initialized += GameServer_Initialized;
        }

        /// <summary>
        /// Gets the world.
        /// </summary>
        public IWorld World { get; private set; }

        /// <summary>
        /// Handles the Load event of the WorldSelectorForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void WorldSelectorForm_Load(object sender, EventArgs e)
        {
            gameServer.Initialize(DIVOKE_KMENE_ADDRESS);
        }

        /// <summary>
        /// Handles the Initialized event of the GameServer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void GameServer_Initialized(object sender, EventArgs e)
        {
            flowLayoutPanel.Controls.Clear();
            foreach (IWorld world in gameServer.Worlds)
            {
                var worldControl = new WorldControl(world);
                worldControl.WorldInitialized += WorldControl_WorldInitialized;
                flowLayoutPanel.Controls.Add(worldControl);
            }
        }

        private void WorldControl_WorldInitialized(object sender, EventArgs e)
        {
            var worldControl = (WorldControl) sender;
            World = worldControl.World;
            DialogResult = DialogResult.OK;
        }
    }
}